package com.abu.authms.controller;

import com.abu.authms.properties.OauthProperties;
import com.abu.authms.service.AuthService;
import com.abu.exceptionhandler.EduException;
import com.abu.utils.Resp;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.*;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Controller
@RequestMapping("/auth/dd")
@EnableConfigurationProperties(OauthProperties.class)
public class OAuthDDController {


    @Autowired
    private OauthProperties oauthProperties;

    @Autowired
    private AuthService authService;

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public String login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
//        获取token信息
        AuthResponse response = authRequest.login(callback);
        String token = this.authService.checkLogin(response.getData());
        if (StringUtils.isBlank(token)) {
            throw new EduException(20001, "生成token值为空");
        }
        return "redirect:http://localhost:3000?token=" + token;
    }

    private AuthRequest getAuthRequest() {
        return new AuthDingTalkRequest(AuthConfig.builder()
                .clientId(oauthProperties.getClientId())
                .clientSecret(oauthProperties.getClientSecret())
                .redirectUri(oauthProperties.getRedirectUri())
                .build());
    }
}
